﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using TraineeManagement.Models;

namespace TraineeManagement.Models.BusinessObject
{
    public class GenericBusiness<T> where T : class
    {
        protected TraineeManagementDBEntities TMDB { get; set; }

        public GenericBusiness()
        {
            this.TMDB = new TraineeManagementDBEntities();
        }

        public GenericBusiness(TraineeManagementDBEntities DB)
        {
            this.TMDB = DB;
        }

        public List<T> GetAll()
        {
            try
            {
                TraineeManagementDBEntities context = TMDB;
                return TMDB.Set<T>().ToList();
            }
            catch (Exception)
            {

                throw;
            }
        }

        public List<T> GetList(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
        {
            try
            {
                return TMDB.Set<T>().Where(predicate).ToList();

            }
            catch (Exception)
            {

                throw;
            }
        }

        public T GetSingle(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
        {
            try
            {
                return TMDB.Set<T>().FirstOrDefault(predicate);

            }
            catch (Exception)
            {

                throw;
            }
        }

        public void Insert(T entity)
        {
            try
            {
                TMDB.Entry(entity).State = System.Data.EntityState.Added;
                TMDB.SaveChanges();
            }
            catch (Exception)
            {
                throw;
            }
        }

        public void Update(T entity)
        {
            try
            {
                TMDB.Set<T>().Attach(entity);
                TMDB.Entry<T>(entity).State = System.Data.EntityState.Modified;
                TMDB.SaveChanges();
            }
            catch (Exception)
            {
                throw;
            }
        }

        public void Delete(T entity)
        {
            try
            {
                TMDB.Entry(entity).State = System.Data.EntityState.Deleted;
                TMDB.SaveChanges();
            }
            catch
            {
                throw;
            }
        }
    }
}